/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package autodispose;

import io.reactivex.rxjava3.annotations.Nullable;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Atomic container for Throwables including combining and having a
 * terminal state via ExceptionHelper.
 * <p>
 * Watch out for the leaked AtomicReference methods!
 */
final class AtomicThrowable extends AtomicReference<Throwable> {
    private static final long serialVersionUID = 3949248817947090603L;

    /**
     * Atomically adds a Throwable to this container (combining with a previous Throwable is
     * necessary).
     *
     * @param t the throwable to add
     * @return true if successful, false if the container has been terminated
     */
    public boolean addThrowable(Throwable t) {
        return ExceptionHelper.addThrowable(this, t);
    }

    /**
     * Atomically terminate the container and return the contents of the last
     * non-terminal Throwable of it.
     *
     * @return the last Throwable
     */
    @Nullable
    public Throwable terminate() {
        return ExceptionHelper.terminate(this);
    }
}
